package com.engine.zzworkflow.cmd;

import com.engine.common.biz.AbstractCommonCommand;
import com.engine.common.entity.BizLogContext;
import com.engine.core.interceptor.CommandContext;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import weaver.conn.RecordSet;
import weaver.general.Util;

import java.util.HashMap;
import java.util.Map;

/**
 * 会计引擎生回写凭证明细
 */
public class SaveBusinessVouchersCmd extends AbstractCommonCommand<Map<String,Object>> {

    public SaveBusinessVouchersCmd(Map<String, Object> params) {
        this.params = params;
    }

    @Override
    public BizLogContext getLogContext() {
        return null;
    }

    @Override
    public Map<String, Object> execute(CommandContext commandContext) {

        writeLog("会计引擎生回写凭证开始... params:"+params.toString());
        Map<String,Object> apidatas  = new HashMap<>();
        apidatas.put("code", -1);
        String msg = verifyParams();
        if(!"".equals(msg)) {
            apidatas.put("msg", msg);
            return apidatas;
        }

        //流程id
        String workflowId = Util.null2String(params.get("workflowId"));
        //单据号对应流程lcbm字段
        String lcbm = Util.null2String(params.get("billNo"));
        //会写明细行号
        String mx = Util.null2String(params.get("mx"));

        RecordSet rs = new RecordSet();
        //流程主表名称
        String maintablename = getWfTablenamById(workflowId, rs);
        if("".equals(maintablename)) {
            apidatas.put("msg", "workflowId 未匹配到对应流程表");
            return apidatas;
        }

        //查询流程id
        String mainid = "";
        String sql = "select id from "+maintablename+" where lcbm= ?";
        boolean b = rs.executeQuery(sql, lcbm);
        if(b && rs.next()) {
            mainid = Util.null2String(rs.getString("id"));
        }else {
            apidatas.put("msg", "billNo 未匹配到数据");
            return apidatas;
        }

        //回写明细行数据
        boolean b1 = addMxVoucher(maintablename + "_dt" + mx, mainid, rs);
        if(b1) {
            apidatas.put("code", 0);
            apidatas.put("msg", "success");
        }else {
            apidatas.put("code", -2);
            apidatas.put("msg", "add voucherDatas fail");
        }

        return apidatas;
    }

    /**
     * 回写明细行数据
     * @param mxtablename
     * @param mainid
     * @param rs
     * @return
     */
    private boolean addMxVoucher(String mxtablename, String mainid, RecordSet rs) {
        boolean result = true;

        JSONArray voucherDatas = JSONArray.fromObject(params.get("voucherDatas"));

        String sql = "insert into "+mxtablename+" (mainid,voucherDate,voucherUser,companyCode," +
                "company,voucherDataType,voucherNumber) values(?,?,?,?,?,?,?)";
        for (int i = 0; i < voucherDatas.size(); i++) {
            JSONObject data = voucherDatas.getJSONObject(i);
            //凭证日期
            String voucherDate = data.getString("voucherDate");
            //凭证制单人
            String voucherUser = data.getString("voucherUser");
            voucherUser = changeField(voucherUser, "hrmresource", "workcode", "lastname", rs);
            //所属法人编码
            String companyCode = data.getString("companyCode");
            //所属法人主体
            String company = data.getString("company");
            //凭证类型
            String voucherDataType = data.getString("voucherDataType");
            //凭证号
            String voucherNumber = data.getString("voucherNumber");

            boolean b = rs.executeUpdate(sql, mainid, voucherDate, voucherUser, companyCode,
                    company, voucherDataType, voucherNumber);

            writeLog("会计引擎生回写凭证明细sql:"+sql+" ("+mainid+","+voucherDate+","+voucherUser+","+companyCode+","
                    +company+","+voucherDataType+","+voucherNumber+")   resflag="+b);
            if(!b) {
                result = false;
            }
        }

        return result;
    }

    /**
     * 验证入参
     * @return
     */
    private String verifyParams() {
        //流程id
        String workflowId = Util.null2String(params.get("workflowId"));
        if("".equals(workflowId)) {
            return "workflowId is null";
        }
        //单据号对应流程requestid
        String requestid = Util.null2String(params.get("billNo"));
        if("".equals(workflowId)) {
            return "billNo is null";
        }
        //会写明细行号
        String mx = Util.null2String(params.get("mx"));
        if("".equals(workflowId)) {
            return "mx is null";
        }

        return "";
    }

    /**
     * 根据workflowid 获取流程表单名称
     * @param workflowid
     * @param rs
     * @return
     */
    private String getWfTablenamById(String workflowid, RecordSet rs) {
        String sql = "select t2.tablename from workflow_base t1 " +
                "left join workflow_bill t2 on t1.formid = t2.id where t1.id = ?";
        boolean b = rs.executeQuery(sql, workflowid);
        if(b && rs.next()) {
            return Util.null2String(rs.getString(1));
        }else {
            return "";
        }
    }


    /**
     * 字段转换
     * @param value
     * @param tablename
     * @param oldField
     * @param newField
     * @param rs
     * @return
     */
    private String changeField(String value, String tablename, String oldField, String newField, RecordSet rs) {
        String sql = "select "+newField+" from "+tablename+" where "+oldField+" = ?";
        boolean b = rs.executeQuery(sql, Util.null2String(value));
        if(b && rs.next()) {
            return Util.null2String(rs.getString(1));
        }else {
            return "";
        }
    }

}
